package com.zhongy.util.util.classloader;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
/**
 * 
 *
 *PluginClassLoader
 *zhongy
 *2015年1月12日-下午2:29:36
 *@version 1.0.0
 */
public class PluginClassLoader extends URLClassLoader  {

	 private List<JarURLConnection> cachedJarFiles = new ArrayList<JarURLConnection>();
	    public PluginClassLoader() {
	        super(new URL[] {});
	    }

	    /**
	     * 将指定的文件url添加到类加载器的classpath中去，并缓存jar connection，方便以后卸载jar
	     * @param 一个可想类加载器的classpath中添加的文件url
	     */
	    public void addURLFile(URL file) {
	        try {
	            // 打开并缓存文件url连接
	            
	            URLConnection uc = file.openConnection();
	            if (uc instanceof JarURLConnection) {
	                uc.setUseCaches(true);
	                ((JarURLConnection) uc).getManifest();
	                cachedJarFiles.add((JarURLConnection)uc);
	            }
	        } catch (Exception e) {
	            System.err.println("Failed to cache plugin JAR file: " + file.toExternalForm()+e.getMessage());
	        }
	        addURL(file);
	    }
	    
	    /**
	     * 卸载jar包
	     */
	    public void unloadJarFiles() {
	        for (JarURLConnection url : cachedJarFiles) {
	            try {
	                System.err.println("Unloading plugin JAR file " + url.getJarFile().getName());
	                System.out.println("Unloading plugin JAR file " + url.getJarFile().getName());
	                url.getJarFile().close();
	                url=null;
	            } catch (Exception e) {
	                System.err.println("Failed to unload JAR file\n"+e);
	                System.out.println("Failed to unload JAR file\n"+e);
	            }
	        }
	    }

	    /**
	     * 定位基于当前上下文的父类加载器
	     * @return 返回可用的父类加载器.
	     */
	    private static ClassLoader findParentClassLoader() {
	        ClassLoader parent = PluginManager.class.getClassLoader();
	        if (parent == null) {
	            parent = PluginClassLoader.class.getClassLoader();
	        }
	        if (parent == null) {
	            parent = ClassLoader.getSystemClassLoader();
	        }
	        return parent;
	    }
	public static void main(String[] args) throws MalformedURLException, ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException {
		ClassLoader myloader=new URLClassLoader(new URL[]{new URL("file:E:/hotLib/")});
		Class<?> c=myloader.loadClass("supply.Trade1");
		Method method=c.getMethod("queryStatus", List.class);
		method.invoke(null,new ArrayList<Object>());
	}
	
	
	
	
}
